package com.mlink.ai.chat.utils

import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import androidx.annotation.ColorInt

class ClickableColorText(text: CharSequence) : SpannableStringBuilder(text) {

    data class ClickableText(
        val text: String,
        val color: Int,
        val onClick: (() -> Unit)? = null
    )

    private val clickableTexts = mutableListOf<ClickableText>()

    fun addClickableText(text: String, @ColorInt color: Int, onClick: (() -> Unit)? = null) {
        val start = this.indexOf(text)
        if (start != -1) {
            val end = start + text.length
            setSpan(
                object : ClickableSpan() {
                    override fun onClick(widget: View) {
                        onClick?.invoke()
                    }

                    override fun updateDrawState(ds: TextPaint) {
                        ds.color = color
                        ds.isUnderlineText = false
                    }
                },
                start,
                end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            clickableTexts.add(ClickableText(text, color, onClick))
        }
    }

    fun getClickableTexts(): List<ClickableText> {
        return clickableTexts
    }

}
